<template>
    <a-row>
      <div class="titleBar" v-if="!type">
        <span>寻源发布</span>
        <div>
          <a-button type="primary" @click="save(1)">暂存</a-button>
          <a-button type="primary" @click="save(2)">保存并发布</a-button>
          <!-- <a-button>返回</a-button> -->
        </div>
      </div>
      <div>
        <a-card>
          <a-steps :current="stepCurrent">
            <a-step title="寻源发起" />
            <a-step title="供应商报价" />
            <a-step title="项目完成" />
          </a-steps>
        </a-card>
        <a-form-model ref="form" :model="form" v-bind="layout">

          <a-card class="MT10" title="基础信息">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="项目名称" :rules='[{ message: "项目名称。", required: true }]' prop="projectTitle">
                  <a-input v-if="type != 'detail'" placeholder="项目名称" v-model="form.projectTitle" />
                  <span v-else>{{ form.projectTitle }}</span>
                  
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="项目编号" prop="projectNum" :rules='[{ message: "项目编号", required: true }]'>
                  <div v-if="type != 'detail'" style="display: flex;justify-content: space-between;">
                    <a-input placeholder="请输入项目编号或点击自动生成" v-model="form.projectNum" />
                    <a-button type="link" @click="autoProjectNum">自动生成</a-button>
                  </div>
                  <span v-else>{{ form.projectNum }}</span>
                  
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="预算金额/元：" :rules='[{ message: "预算金额/元", required: true }]' prop="budgetAmount">
                  <a-input-number v-if="type != 'detail'" style="width: 100%;" v-model="form.budgetAmount" :min="0" :precision='2'
                    placeholder="预算金额/元" />
                  <span v-else>{{ form.budgetAmount }}</span>

                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="报价截止时间：" :rules='[{ message: "报价截止时间", required: true }]'
                  prop="quotationDeadline">
                  <a-date-picker v-if="type != 'detail'" v-model="form.quotationDeadline" show-time style="width: 100%;"
                    format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" placeholder="请选择" />
                  <span v-else>{{ form.quotationDeadline }}</span>

                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="项目联系人" :rules='[{ message: "项目联系人", required: true }]' prop="person">
                  <a-input v-if="type != 'detail'" placeholder="项目联系人" v-model="form.person" />
                  <span v-else>{{ form.person }}</span>

                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="联系方式" prop="phone"
                  :rules='[{ message: "联系方式", required: true }, { message: "手机号码格式不正确", pattern: validators.rules().phoneReg }]'>
                  <a-input v-if="type != 'detail'" placeholder="请输入联系方式" v-model="form.phone" />
                  <span v-else>{{ form.phone }}</span>

                </a-form-model-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card style="margin-top: 20px" title="标的清单" :headStyle="tstyle">
            <a-row>
              <a-table :dataSource="productData" :pagination="false" rowKey="key" id="productDataTable"
                :scroll="{ x: 1350 }">
                <a-table-column title="序列" align="center" width="60px">
                  <template slot-scope="text, record, index">
                    <div style="width: 40px">{{ index + 1 }}</div>
                  </template>
                </a-table-column>
                <a-table-column data-index="goodsTypeIdObj" key="goodsTypeIdObj" align="center" width="160px">
                  <span slot="title">
                    <span class="redFont">*</span>
                    所属类目
                  </span>
                  <template slot-scope="text, record, index">
                    <a-select v-if="type!='detail'" labelInValue v-model="record.goodsTypeIdObj" @change="goodsTypeChange($event, index)"
                      style="width:130px;" :key="index">
                      <a-select-option v-for="(item, index) in goodsList" :key="index" :value="item.id">{{ item.name }}
                      </a-select-option>
                    </a-select>
                    <span v-else>{{ record.goodsTypeName }}</span>
                  </template>
                </a-table-column>
                <a-table-column data-index="goodsName" key="goodsName" align="center" width="150px">
                  <span slot="title">
                    <span class="redFont">*</span>
                    标的名称
                  </span>
                  <template slot-scope="text, record, index">
                    <a-input v-if="type!='detail'" placeholder="请输入标的名称" style="width: 130px" v-model="record.goodsName"
                      @blur="changeProductName(record, index)" />
                    <span v-else>{{ record.goodsName }}</span>

                  </template>
                </a-table-column>
                <a-table-column data-index="purchaseNum" key="purchaseNum" align="center" width="150px">
                  <span slot="title">
                    <span class="redFont">*</span>
                    采购数量
                  </span>
                  <template slot-scope="text, record">
                    <a-input-number v-if="type!='detail'" placeholder="请输入" :min="1"
                      :parser="value => (/^(\-)*(\d+)$/.test(value) ? value : 1)" style="width: 130px"
                      v-model="record.purchaseNum" />
                    <span v-else>{{ record.purchaseNum }}</span>

                  </template>
                </a-table-column>
                <a-table-column data-index="unit" align="center" width="150px">
                  <span slot="title">
                    <span class="redFont">*</span>
                    计量单位
                  </span>
                  <template slot-scope="text, record">
                    <a-input v-if="type!='detail'" placeholder="请输入" style="width: 130px" v-model="record.unit" />
                    <span v-else>{{ record.unit }}</span>

                  </template>
                </a-table-column>

                <a-table-column data-index="indicatorRequirements" align="center" width="150px">
                  <span slot="title">
                    <span class="redFont">*</span>
                    技术指标和服务要求
                  </span>
                  <template slot-scope="text, record, index">

                    <a-textarea v-if="type!='detail'" placeholder="请输入" style="width: 140px" v-model="record.indicatorRequirements"
                      :autoSize="{ minRows: 1 }" />
                    <span v-else>{{ record.indicatorRequirements }}</span>

                  </template>
                </a-table-column>



                <a-table-column title="操作" align="center" width="100px">
                  <template slot-scope="text, record, index">
                    <a-popconfirm v-if="productData.length&&type != 'detail'" title="确定删除?" @confirm="() => onDelete(index)">
                      <div style="width: 40px; margin-left: 20px;cursor: pointer;color: red;">
                        删除
                      </div>
                    </a-popconfirm>
                    <span v-else>~</span>
                  </template>
                </a-table-column>

              </a-table>
              <a-row class="newT-btn"  v-if="type != 'detail'">
                <div @click="pushNewObj"><a-icon type="plus-square" />添加标的</div>
              </a-row>
            </a-row>
          </a-card>
          <a-card class="MT10" title="供应商信息及要求">
            <a-row>
              <a-col :span="12">
                <a-form-model-item :rules='[{ message: "邀请方式", required: true }]' prop="supplySelMeth">
                  <span slot="label">
                    邀请方式
                    <a-tooltip>
                      <template slot="title">
                        邀请供应商仅限付费供应商方可参与后续的报价业务，如若指定供应商未购买会员可自行通知供应商购买会员<br />
                      </template>
                      <a-icon type="info-circle" />
                    </a-tooltip>
                  </span>
                  <a-radio-group v-model="form.supplySelMeth" :disabled="type=='detail'">
                    <a-radio :value="1">
                      公开邀请
                    </a-radio>
                    <a-radio :value="2">
                      指定邀请
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :rules='[{ message: "是否公开展示", required: true }]' prop="publicDisplay">

                  <span slot="label">
                    是否公开展示
                    <a-tooltip>
                      <template slot="title">
                        选择"是"则默认在寻源大厅展示，选择"否"则不做展示<br />
                      </template>
                      <a-icon type="info-circle" />
                    </a-tooltip>
                  </span>
                  <a-radio-group v-model="form.publicDisplay" :disabled="type=='detail'">
                    <a-radio :value="1">
                      是
                    </a-radio>
                    <a-radio :value="0">
                      否
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="结算方式" :rules='[{ message: "结算方式", required: true }]' prop="tradeMode">
                  <a-radio-group v-model="form.tradeMode" :disabled="type=='detail'">
                    <a-radio :value="1">
                      款到发货
                    </a-radio>
                    <a-radio :value="2">
                      货到付款
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="含税要求" :rules='[{ message: "含税要求", required: true }]' prop="taxRequest">
                  <a-radio-group v-model="form.taxRequest" :disabled="type=='detail'">
                    <a-radio :value="1">
                      含税
                    </a-radio>
                    <a-radio :value="2">
                      不含税
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="运费要求" :rules='[{ message: "运费要求", required: true }]' prop="fareRequest">
                  <a-radio-group v-model="form.fareRequest" :disabled="type=='detail'">
                    <a-radio :value="1">
                      含运费
                    </a-radio>
                    <a-radio :value="0">
                      不含运费
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="发票要求" :rules='[{ message: "发票要求", required: true }]' prop="billRequest">
                  <a-radio-group v-model="form.billRequest" :disabled="type=='detail'">
                    <a-radio :value="1">
                      增值税专用发票
                    </a-radio>
                    <a-radio :value="2">
                      增值税普通发票
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="form.supplySelMeth == 2">
              <a-table :dataSource="supplierData" :pagination="false" rowKey="key">
                <a-table-column title="序列" style="text-align: center">
                  <template slot-scope="text, record, index">
                    <div style="width: 40px">{{ index + 1 }}</div>
                  </template>
                </a-table-column>
                <a-table-column title="供应商名称" data-index="supplierName" key="supplierName" style="text-align: center">
                  <template slot-scope="text, record">
                    <a-select v-if="type!='detail'" showSearch style="width: 200px" :showArrow="false" :filterOption="false" labelInValue
                      :defaultOpen="false" @search="fetchSupplier(arguments[0], 'search')"
                      @focus="fetchSupplier('', 'focus')" @change="getAllSupplierData(arguments[0], record)"
                      placeholder="请选择供应商名称" class="select-w" notFoundContent="暂无数据" v-model="record.labelInValue"
                      :getPopupContainer="triggerNode => {
            return triggerNode.parentNode || document.body;
          }
            ">
                      <a-select-option v-for="d in fetchSupplierData" :key="d.supplierId">{{
            d.supplierName
          }}</a-select-option>
                    </a-select>
                    <span v-else>{{ record.supplierName }}</span>
                  </template>
                </a-table-column>
                <a-table-column title="统一社会信用代码" data-index="uscc " key="uscc" style="text-align: center"
                  :read-only="true">
                  <template slot-scope="text, record">
                    <a-input v-if="type!='detail'" placeholder="请输入" style="width: 150px;" v-model="record.uscc" :read-only="true" />
                    <span v-else>{{ record.uscc }}</span>

                  </template>
                </a-table-column>
                <a-table-column title="联系人" data-index="person">
                  <template slot-scope="text, record">
                    <a-input v-if="type!='detail'" placeholder="请输入" v-model="record.person" />
                    <span v-else>{{ record.person }}</span>

                  </template>
                </a-table-column>
                <a-table-column title="联系电话" data-index="phone">
                  <template slot-scope="text, record">
                    <a-input v-if="type!='detail'" placeholder="请输入" v-model="record.phone" />
                    <span v-else>{{ record.phone }}</span>

                  </template>
                </a-table-column>
                <a-table-column title="是否付费会员" data-index="email" align="center">
                  <template slot-scope="text, record">
                    {{ record.isPay == 1 ? '是' : '否' }}
                  </template>
                </a-table-column>
                <a-table-column title="操作">
                  <template slot-scope="text, record, index">
                    <a-popconfirm v-if="supplierData.length&&type != 'detail'" title="确定删除?" @confirm="() => supplierOnDelete(index)">
                      <div class="take-s-btn primary_btn_color" style="width: 40px;cursor: pointer;color: red;">
                        删除
                      </div>
                    </a-popconfirm>
                    <span v-else>~</span>
                  </template>
                </a-table-column>
              </a-table>
              <a-row class="newT-btn" v-if="type != 'detail'">
                <div @click="addSupplier"><a-icon type="plus-square" />添加供应商</div>
              </a-row>
            </a-row>
          </a-card>
          <a-card class="MT10" title="商务要求">
            <a-row>
              <a-col :span="24">
                <a-form-model-item :labelCol="{ span: 3 }" :wrapperCol="{ span: 18 }" label="商务要求"
                  prop="businessRequest">
                  <a-textarea placeholder="请输入商务要求" :disabled="type=='detail'" :rows="3" v-model="form.businessRequest"
                    :maxLength="200"></a-textarea>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="上传附件" prop="fileUrl" :labelCol="{ span: 3 }" :wrapperCol="{ span: 18 }">
                  <Upload :isDisabled="type=='detail'" :defaultFileList="form.fileUrl" @change="upload" accept=".doc,.docx,.pdf,.word,.zip,.rar"
                    :max-num="1" showHint hint="支持扩展名：.xls,.xlsx,.doc,.docx,.pdf,.jpg,.png"></Upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form-model>
      </div>
    </a-row>
</template>

<script>
import storage from '@/utils/storage'
import { goodsTypeList, querySupplierLibrary } from "@/api/goods/type.js";
import { saveSourcingInfo, nextVal,getSourcingBaseInfo  } from "@/api/sourcing/index.js";

import { isEmpty } from '@/utils/func.js'
import Upload from "@/components/upload/Upload";


export default {
  components: {
    Upload
  },
  props: {
    type: ''
  },
  data() {
    return {
      stepCurrent: 0,
      sourcingStep: [
        [
          {
            title: 'Finished',
          },
          {
            title: 'In Progress',
            subTitle: 'Left 00:00:08',
          },
          {
            title: 'Waiting',
          },
        ]
      ],
      form: {
        fileUrl: [],
        projectTitle: undefined,
        billRequest: undefined,
        budgetAmount: undefined,
        businessRequest: undefined,
        fareRequest: undefined,
        person: undefined,
        phone: undefined,
        projectNum: undefined,
        publicDisplay: undefined,
        quotationDeadline: undefined,
        sourcingFlow: undefined,
        supplySelMeth: undefined,
        taxRequest: undefined,
        tradeMode: undefined
      },
      layout: {
        labelCol: { span: 7 },
        wrapperCol: { span: 17 },
      },
      tstyle: {
        color: "rgba(50,50,50,1)",
        "font-weight": "500",
        "font-size": "16px"
      },
      productData: [],
      supplierData: [],
      goodsList: [],
      fetchSupplierData: [],
      id: ""
    }
  },
  mounted() {
    this.getGoodsList()
    this.getSupplierList()
    console.log('===',this.id)
    this.id = this.$route.query.id

    if(this.id) {
      this.getDetail()
    }
  },
  methods: {
    getDetail() {
      getSourcingBaseInfo({id: this.id}).then(res =>{
        if(res.code ==0) {
          res.data.fileUrl = res.data.fileUrl.split(',')
          res.data.fileUrl = res.data.fileUrl.map((item, index) => {
            return {
              uid: index, name: '附件'+ +index+1, status: 'done', url: item

            }
          })
          res.data.sourcingTargetList = res.data.sourcingTargetList.map(item => {
            return {
              goodsTypeIdObj: {label: item.goodsTypeName,key: item.goodsTypeId},
              ...item
            }
          })
          if(res.data.sourcingInviteSupplierList) {
            res.data.sourcingInviteSupplierList = res.data.sourcingInviteSupplierList.map(item => {
            return {
              labelInValue: {label: item.supplierName,key: item.supplierId},
              ...item
            }
          })
          }
         
        
          this.productData = res.data.sourcingTargetList
          this.supplierData = res.data.sourcingInviteSupplierList

          this.stepCurrent = +res.data.status -1
          this.form = {...res.data}
          this.$emit('getDetail',this.form)
        }
      })
    },
    onDelete(key) {
      this.productData.splice(key, 1);
    },
    supplierOnDelete(key) {
      this.supplierData.splice(key, 1);
    },
    goodsTypeChange(val, index) {
      this.$set(this.productData[index], 'goodsTypeName', val.label)
      this.$set(this.productData[index], 'goodsTypeId', val.key)
      console.log(val, 'goodsTypeChange')
    },
    upload(file, fileList) {
      console.log(fileList, 'file')
      this.form.fileUrl = fileList
    },
    autoProjectNum() {
      nextVal({ serviceType: 'sourcingNo' }).then(res => {
        if (res.code == 0) {
          this.form.projectNum = res.data
        }
      })
    },
    pushNewObj() {
      this.productData.push({
        goodsName: undefined,
        goodsTypeId: undefined,
        goodsTypeIdObj: undefined,
        goodsTypeName: undefined,
        indicatorRequirements: undefined,
        purchaseNum: undefined,
        unit: undefined
      })
    },
    addSupplier() {
      this.supplierData.push({
        isPay: 1,
        labelInValue: undefined,
        person: undefined,
        phone: undefined,
        supplierId: undefined,
        supplierName: undefined,
        uscc: undefined
      })
    },
    getGoodsList() {
      goodsTypeList({ level: 3 }).then(res => {
        if (res.code == 0) {
          this.goodsList = res.data
        }
      })
    },
    //查找供应商
    fetchSupplier(value) {
      this.getSupplierList(value);
    },
    getAllSupplierData(arg, record) {
      let fetchSupplier = {};
      for (let item of this.fetchSupplierData) {
        if (arg.key === item.supplierId) {
          fetchSupplier = item;
          break;
        }
      }
      record.isPay = 1;
      record.person = fetchSupplier.legalRepresent;
      record.phone = fetchSupplier.contactPhone;
      record.supplierId = fetchSupplier.supplierId;
      record.supplierName = fetchSupplier.supplierName;
      record.uscc = fetchSupplier.uscc;
    },
    getSupplierList(name) {
      if (isEmpty(name)) {
        name = undefined
      }
      querySupplierLibrary({
        reviewStatus: '1',
        supplierName: name
      }).then(res => {
        if (res.code == 0) {
          this.fetchSupplierData = res.data.records
        }
      })
    },
    save(status) {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        if (!this.productData.length) {
          this.$message.info('标的清单不能为空');
          return false
        }
        if (this.form.supplySelMeth == 2 && !this.supplierData.length) {
          this.$message.info('供应商信息不能为空');
          return false
        }
        if (this.productData.some(item => !item.goodsTypeId || !item.goodsName || !item.purchaseNum || !item.unit || !item.indicatorRequirements)) {
          this.$message.info('请完整填写标的清单');
          return false
        }
        if (this.form.supplySelMeth == 2 && this.supplierData.some(item => !item.supplierId || !item.supplierName || !item.phone || !item.person || !item.isPay)) {
          this.$message.info('请完整填写供应商信息');
          return false
        }
        let params = {
          sourcingTargetList: this.productData,
          sourcingFlow: '1',
          status: status,
          ...this.form
        }
        if (this.form.supplySelMeth == '2') {
          params.sourcingInviteSupplierList = this.supplierData
        }
        console.log(this.form.goodsTypeIdObj, 'goodsTypeIdObj')
        if (this.form.fileUrl.length == 0) {
          params.fileUrl = ''
        } else {
          let fileUrlArr = this.form.fileUrl.map(item => {
            return item.url
          })
          params.fileUrl = fileUrlArr.join(',')
        }
        saveSourcingInfo(params).then(res => {
          if (res.code == 0) {
            this.$message.success('成功')
            this.$router.push({
              path: '/mySourcing',
            })
          }
        })
      })
    }
  },
  watch: {

  }
}
</script>

<style lang="scss" scoped>
.userBox {
  padding: 0 24px;
  border-left: 4px solid #cccccc54;
  margin-left: -1px;
  min-height: 650px;
}

.titleBar {
  width: 100%;
  height: 50px;
  line-height: 30px;
  padding: 10px;
  margin-bottom: 20px;
  background: #fff;
  border-bottom: 1px dashed #ccc;
  font-size: 16px;
  color: #333;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
}

.newT-btn {
  height: 40px;
  line-height: 40px;
  width: 100%;
  color: #1890FF;
  border: 1px dashed rgba(226, 226, 226, 1);
  text-align: center;
  cursor: pointer;
  margin-top: 10px;
}

.redFont {
  color: red;
}
</style>